package com.hjy.hjyojbackendquestionservice.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjy.hjyojbackendcommon.common.ErrorCode;
import com.hjy.hjyojbackendcommon.constant.CommonConstant;
import com.hjy.hjyojbackendcommon.constant.OjMqConstant;
import com.hjy.hjyojbackendcommon.exception.BusinessException;
import com.hjy.hjyojbackendcommon.utils.SqlUtils;
import com.hjy.hjyojbackendjudgeservice.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.hjy.hjyojbackendjudgeservice.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.hjy.hjyojbackendjudgeservice.model.entity.Question;
import com.hjy.hjyojbackendjudgeservice.model.entity.QuestionSubmit;
import com.hjy.hjyojbackendjudgeservice.model.entity.User;
import com.hjy.hjyojbackendjudgeservice.model.enums.QuestionSubmitLanguageEnum;
import com.hjy.hjyojbackendjudgeservice.model.enums.QuestionSubmitStatusEnum;
import com.hjy.hjyojbackendjudgeservice.model.vo.QuestionSubmitVO;
import com.hjy.hjyojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.hjy.hjyojbackendquestionservice.rabbitMq.MqMessageProducer;
import com.hjy.hjyojbackendquestionservice.service.QuestionService;
import com.hjy.hjyojbackendquestionservice.service.QuestionSubmitService;
import com.hjy.hjyojbackendserviceclient.service.JudgeServiceClient;
import com.hjy.hjyojbackendserviceclient.service.UserFerignClient;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 提交题目
 *
 * @author 89522
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2024-02-01 11:47:07
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;
    @Resource
    @Lazy
    private JudgeServiceClient judgeService;
    @Resource
    private UserFerignClient userService;
    @Resource
    private MqMessageProducer mqMessageProducer;

    /**
     * 题目提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionSubmitAddRequest.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断用户提交的编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (Objects.isNull(enumByValue)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        // 是否已题目提交
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionSubmitAddRequest.getQuestionId());
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setJudgeInfo("{}");
        //设置题目提交状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        //执行判题服务
        //消息队列发送消息，从而进一步解耦。
        mqMessageProducer.sendMessage(OjMqConstant.OJ_EXCHANGE_NAME,OjMqConstant.OJ_ROUTING_KEY,String.valueOf(questionSubmitId));
//        CompletableFuture.runAsync(() -> {
//            judgeService.dojudge(questionSubmitId);
//        });
        return questionSubmitId;
    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long userId = questionSubmitQueryRequest.getUserId();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.like(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.like(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //脱敏：仅本人和管理员可见，(提交的userId和登录用户id不同)则需要脱敏
        //获取提交用户的id
        long questionSubmitUserId = questionSubmit.getUserId();
        //获取登录用户
        if (!loginUser.getId().equals(questionSubmitUserId) && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser)).collect(Collectors.toList());
        questionSubmitVOPage = questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}



